import React, { useRef, useState } from 'react';
import { PageContainer, ModalForm,ProForm, ProTable,
  ProColumns, ActionType,
  ProFormText, } from '@ant-design/pro-components';
import { roleList, menulist, roleAdd, menuChange } from '@/services/user'
import { Button, message, Tree } from 'antd';
import { useRequest } from 'ahooks';
import { PlusOutlined } from '@ant-design/icons';
function FormTree({ value, onChange, treeData }: any) {
  return <Tree
    checkable
    selectable={false}
    defaultExpandAll
    checkStrictly
    height={253}
    virtual={false}
    checkedKeys={value}
    onCheck={({ checked }: any) => {
      onChange(checked)
    }}
    treeData={treeData}
  />
}
const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>()
  const columns: ProColumns<any>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id'
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName'
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      key: 'gmtCreate'
    },
    {
      title: '状态',
      render: (text, record) => {
        if (record.deleted == false) {
          return '启用'
        } else {
          return '停用'
        }
      }
    },
    {
      title: '操作',
      render: (text, record) => <Button onClick={() => {
        const menuIdList = record.menuIdList
        setMenuIds(menuIdList[0] == '' ? [] : menuIdList)
        setId(record.id)
        setVisible(true)
      }}>权限</Button>
    }
  ]
  const [menuIds, setMenuIds] = useState([])
  const [id, setId] = useState()

  /** 新增角色 */
  const { run: doAdd } = useRequest(roleAdd, {
    manual: true,
    onSuccess: () => {
      message.success('添加成功')
      actionRef.current?.reload();
    }
  })
  /** 修改角色菜单权限 */
  const [visible, setVisible] = useState(false)
  const { run: doChange } = useRequest(menuChange, {
    manual: true,
    onSuccess: () => {
      message.success('修改成功')
      actionRef.current?.reload();
    }
  })
  /**
   * 获取菜单
   */
  function updateTreeData(list: any[]): any[] {
    const treeList: any[] = list.map((node) => ({
      key: node.key,
      title: node.value,
      children: updateTreeData(node.children),
    }))
    return treeList
  }
  const [treeData, settreeData] = useState([])
  useRequest(menulist, {
    onSuccess: (res) => {
      const list = updateTreeData(res[0].treeNode.children)
      settreeData(list) 
    }
  })

  return (
    <PageContainer header={{ breadcrumb: {} }}>
      <ProTable<any, API.PageParams>
        headerTitle='角色列表'
        actionRef={actionRef}
        rowKey="id"
        size='large'
        search={{
          labelWidth: 100,
        }}
        toolBarRender={() => [
          <ModalForm
            width='300px'
            trigger={
              <Button type="primary">
                <PlusOutlined />
                添加角色
              </Button>
            }
            modalProps={{
              destroyOnClose: true,
              centered: true
            }}
            onFinish={async (values: any) => {
              await doAdd({ ...values });
              return true;
            }}
          >
            <ProFormText
              label='角色名称'
              name='roleName'
              rules={[{
                required: true,
                message: '角色名称必填'
              }]}
            />
          </ModalForm>,
        ]}
        pagination={false}
        request={async (PageParams) => {
          const res = await roleList({ ...PageParams, pageIndex: PageParams.current })
          return {
            data: res,
            success: true,
          }
        }}
        columns={columns}
      />
      <ModalForm
        width='500px'
        visible={visible}
        title="修改权限"
        onVisibleChange={(visible) => {
          setVisible(visible)
        }}
        modalProps={{
          destroyOnClose: true,
          centered: true
        }}
        onFinish={async (values: any) => {
          await doChange({ ...values, id })
          return true
        }}
        initialValues={{ menuIds }}
      >
        <ProForm.Item
          name='menuIds'
          label='菜单权限'
        >
          <FormTree treeData={treeData} />
        </ProForm.Item>
      </ModalForm>
    </PageContainer>
  );
};

export default TableList;
